<template>
  <!-- 监控区域 -->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="区域名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="父区域" prop="psectorName">
        <el-input
          v-model="queryParams.psectorName"
          placeholder="请输入父区域"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bm:monitor:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bm:monitor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bm:monitor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bm:monitor:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="monitorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" width="55" prop="id" />
      <el-table-column label="区域略图" align="center" prop="sectorPicPath">
        <template slot-scope="scope">
          <el-image 
            style="width: 100px; height: 100px"
            :src="scope.row.sectorPicPath"
            :preview-src-list="[scope.row.sectorPicPath]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="父区域" align="center" prop="psectorName" />
      <el-table-column label="区域名称" align="center" prop="name" />
      <el-table-column label="区域功能描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bm:monitor:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bm:monitor:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监控区域对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域略图" prop="sectorPicPath">
          <el-upload
            class="upload-demo"
            :action="uploadFileUrl"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false">
            <el-image
              v-if="form.sectorPicPath"
              :src="form.sectorPicPath"
              style="width: 100px; height: 100px"
            />
            <el-button v-else size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="功能描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="父区域id" prop="monitorId">
          <el-input v-model.number="form.monitorId" placeholder="请输入父区域id" />
        </el-form-item>
        <el-form-item label="排序顺序" prop="sortIndex">
          <el-input v-model.number="form.sortIndex" placeholder="请输入排序顺序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMonitor, getMonitor, delMonitor, addMonitor, updateMonitor } from "@/api/mes/bm/monitor";
import { getToken } from "@/utils/auth";

export default {
  name: "Monitor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监控区域表格数据
      monitorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,        psectorName: null,      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sectorPicPath: [
          { required: true, message: "区域略图不能为空", trigger: "blur" }
        ],        name: [
          { required: true, message: "区域名称不能为空", trigger: "blur" }
        ],        description: [
          { required: true, message: "区域功能描述不能为空", trigger: "blur" }
        // ],        monitorId: [
        //   { required: true, message: "父区域id不能为空", trigger: "blur" }
        ],        psectorName: [
          { required: true, message: "父区域名字，与父区域id对应，存储上级区域的名称不能为空", trigger: "blur" }
        ],        isLock: [
          { required: true, message: "被锁状态，表示监控点是否被锁定，防止修改或删除不能为空", trigger: "blur" }
        ],        sortIndex: [
          { required: true, message: "排序顺序不能为空", trigger: "blur" }
        ],        type: [
          { required: true, message: "类型，表示监控点的类别或功能不能为空", trigger: "change" }
        ],        showInBigscreen: [
          { required: true, message: "是否在大屏幕显示", trigger: "blur" }
        ]      },
      // 上传的图片路径
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/uploadMinio", // 这里需要后端提供上传接口
      // 设置上传头
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询监控区域列表 */
    getList() {
      this.loading = true;
      listMonitor(this.queryParams).then(response => {
        this.monitorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        
        sectorPicPath: null,        
        name: null,        
        description: null,        
        monitorId:0,        
        psectorName: null,        
        isLock: false,        
        sortIndex: 0,        
        type: null,        
        showInBigscreen: false      
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加监控区域";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMonitor(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改监控区域";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMonitor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMonitor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除监控区域编号为"' + ids + '"的数据项？').then(function() {
        return delMonitor(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/bm/monitor/export', {
        ...this.queryParams
      }, `monitor_${new Date().getTime()}.xlsx`)
    },
    // 上传前的校验
    beforeUpload(file) {
      const isImage = file.type.indexOf('image') !== -1;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.form.sectorPicPath = res.url; // 假设后端返回的是 MinIO 的访问 URL
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败');
      }
    },
    // 上传失败回调
    handleUploadError() {
      this.$message.error('上传失败');
    },
  }
};
</script>

<style scoped>
.upload-demo {
  text-align: center;
}
</style>
